<template>
  <div class="welcome-container-warpper">
    <div class="welcome-container">
      <div class="welcome-main">
        <h1 class="color-main">
          <SvgIcon iconClass="success"></SvgIcon>注册成功
        </h1>
        <h2 style="color: #606266">恭喜您已成功注册为平台用户!</h2>
        <div style="color: #909399; font-size: 14px">
          您可以选择前往设置个人信息或者跳转到首页，祝您使用愉快!
        </div>
        <div>
          <el-button
            style="margin-top: 20px"
            type="primary"
            round
            @click="handleGoSetting"
            >编辑资料</el-button
          >
          <el-button
            style="margin-top: 20px"
            type="primary"
            round
            @click="handleGoMain"
            >返回首页</el-button
          >
        </div>
      </div>
    </div>
    <el-dialog
      title="设置兴趣"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      center
    >
      <el-alert
        style="margin-bottom: 20px"
        title="请选择添加兴趣标签，每个用户至多添加5条不同的兴趣标签"
        type="info"
        show-icon
        :closable="false"
        effect="dark"
      >
      </el-alert>
      <el-tag
        v-for="(tag, index) in selectedTags"
        :key="index"
        type="success"
        closable
        :disable-transitions="false"
        :hit="true"
        @close="handleClose(tag)"
        style="margin-bottom: 10px"
      >
        {{ tag.name }}</el-tag
      >
      <el-autocomplete
        class="input-new-tag"
        v-model="inputValue"
        :fetch-suggestions="querySearch"
        placeholder="请输入内容"
        v-if="inputVisible"
        ref="saveTagInput"
        :trigger-on-focus="true"
        @keyup.enter.native="handleInputConfirm"
        @select="handleSelect"
        size="small"
      >
        <!-- @blur="handleInputConfirm" -->
      </el-autocomplete>
      <el-button
        v-else
        class="button-new-tag"
        size="small"
        @click="showInput"
        :disabled="selectedTags.length >= 5"
        >{{
          selectedTags.length >= 5
            ? "每个用户最多添加5条兴趣标签"
            : "+ 添加兴趣"
        }}</el-button
      >
      <el-divider></el-divider>
      <el-row :gutter="20">
        <el-col :span="4"><h2>猜您喜欢</h2></el-col>
        <el-col :span="4" :offset="16">
          <el-button size="small" icon="el-icon-refresh" @click="handleRefresh">
            换一组
          </el-button>
        </el-col>
      </el-row>
      <el-button
        v-for="item in randomTags"
        type="text"
        :key="item.id"
        :style="{
          color: setColor(),
          width: '17%',
          'margin-top': '15px',
          fontSize: setFontSize(),
        }"
        @click="handleClick(item)"
        :disabled="hasSelected(item)"
        >{{ item.name }}</el-button
      >
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确定</el-button>
        <el-button @click="dialogVisible = false">跳过</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRandomTags, queryAllTags } from "@/api/tags";
import { saveUserInterestTags } from "@/api/user";
export default {
  data() {
    return {
      // 只有首次注册成功时需要设置，其他情况下默认不设置(如用户手动转到该页面)
      dialogVisible: this.$route.params.dialogVisible === true ? true : false,
      // 所有标签
      tags: [],
      // 选择的兴趣标签
      selectedTags: [],
      // 最多选择5个兴趣标签
      selectedLimit: 5,
      loading: false,
      options: [],
      inputVisible: false,
      inputValue: "",
      randomTags: [],
      randomTagsQuery: {
        pageNum: 1,
        pageSize: 20,
      },
      colorList: [],
      fontSizeList: [],
    };
  },
  created() {
    this.getAllTags();
    this.handleGetRandomTags();
    this.selectedTags = [];
  },
  methods: {
    getAllTags() {
      // 查询所有标签
      queryAllTags().then((res) => {
        var list = res.data;
        this.tags = list.map((item) => {
          return { id: item.id, name: item.name };
        });
      });
    },
    handleGetRandomTags() {
      // 查询随机固定个数的标签
      getRandomTags(this.randomTagsQuery).then((res) => {
        var list = res.data;
        this.randomTags = [];
        for (let index = 0; index < list.length; index++) {
          const element = list[index];
          this.randomTags.push({ id: element.id, name: element.name });
        }
      });
    },
    querySearch(queryString, cb) {
      var tags = this.tags;
      var result = queryString
        ? tags.filter((tag) => tag.name.indexOf(queryString) > -1)
        : tags;
      var out = [];
      result.forEach((tag) => {
        out.push({ id: tag.id, name: tag.name, value: tag.name });
      });
      cb(out);
    },
    handleGoMain() {
      // 跳转到主页
      this.$router.push({ name: "home" });
    },
    handleGoSetting() {
      // 跳转到个人信息编辑页
      this.$router.push({ name: "user-center-setting" });
    },
    handleClose(tag) {
      // 取消选择某个标签
      this.selectedTags.splice(this.selectedTags.indexOf(tag), 1);
    },
    showInput() {
      // 光标定位
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      // 处理回车逻辑
      let inputValue = this.inputValue;
      if (inputValue) {
        let item = this.getTagByName(inputValue);
        if (item && !this.hasSelected(item) && !this.hasReachedLimit()) {
          // 如果该标签在所有标签中，且非已选，则添加
          this.selectedTags.push({ id: item.id, name: item.name });
        }
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    inAllTags(item) {
      // 判断在所有tag中
      let tags = this.tags;
      for (let i = 0; i < tags.length; i++) {
        if (item.id === tags[i].id) {
          return true;
        }
      }
      return false;
    },
    hasSelected(item) {
      // 判断是否已选
      let selectedTags = this.selectedTags;
      
      for (let i = 0; i < selectedTags.length; i++) {
        if (item.id === selectedTags[i].id) {
          return true;
        }
      }
      return false;
    },
    hasReachedLimit() {
      return this.selectedTags.length >= this.selectedLimit;
    },
    getTagByName(inputValue) {
      // 根据name获取同名tag item
      return this.tags.filter((tag) => tag.name === inputValue)[0];
    },
    setColor() {
      let r = Math.floor(Math.random() * 256);
      let g = Math.floor(Math.random() * 256);
      let b = Math.floor(Math.random() * 256);
      let color = "#" + r.toString(16) + g.toString(16) + b.toString(16);
      return color;
    },
    setFontSize() {
      let fontSize = Math.floor(Math.random() * 5) + 18;
      return fontSize + "px";
    },
    handleClick(item) {
      if (
        item &&
        this.inAllTags(item) &&
        !this.hasSelected(item) &&
        !this.hasReachedLimit()
      ) {
        this.selectedTags.push({ id: item.id, name: item.name });
      }
    },
    handleRefresh() {
      this.handleGetRandomTags();
    },
    handleSelect(item) {
      this.handleInputConfirm();
    },
    handleSubmit() {
      this.dialogVisible = false;
      saveUserInterestTags(this.selectedTags).then((res) => {
        this.$message({
          message: "保存成功",
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.welcome-container-warpper {
  width: 100%;
  position: absolute;
  background-image: url("../../assets/images/elaine-casap-qgHGDbbSNm8-unsplash.jpg");
  background-position: center center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
  height: calc(100% - 56px);
}
.welcome-container {
  width: 80%;
  margin: 0 auto;
}
.welcome-main {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  background-color: #e9eef3;
  text-align: center;
  line-height: 100px;
  margin-top: 100px;
}
.success-logo {
  width: 60px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
  width: 200px;
}
.input-new-tag {
  width: 200px;
  margin-left: 10px;
}
</style>